package com.itheima.sh.f_ajax_json_test_06;

import com.alibaba.fastjson.JSON;
import com.itheima.sh.c_filter_03.loginFilter.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

//3.请求参数和响应都是json格式数据
@WebServlet("/ajaxJsonTest03Servlet")
public class AjaxJsonTest03Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //请求数据为json格式
            User user = JSON.parseObject(request.getInputStream(), User.class);

            ArrayList<Friend> list = new ArrayList<>();
            Collections.addAll(list, new Friend(1, "柳岩", 18),
                    new Friend(2, "杨幂", 19),
                    new Friend(3, "李沁", 20));


            //响应的是json格式
//        String s = JSON.toJSONString(list);
//        response.getWriter().print(s);

            //创建Result对象，封装响应的结果信息，查询成功：
            Result result = new Result(true, "查询好友列表成功", list);
//            有了BaseController工具类后，以下代码不需要了
//            //将result对象转换为json格式数据
//            String str = JSON.toJSONString(result);
//            //响应给前端
//            response.getWriter().print(str);
            BaseController.printJsonToBrowser(result,response);

        } catch (Exception e) {
            //打印错误信息
            e.printStackTrace();
            //查询失败
            //创建响应结果类的对象
            //Result result = new Result(false, "查询好友列表失败");
            //有了BaseController工具类后，以下代码不需要了
//            //将result对象转换为json格式数据
//            String str = JSON.toJSONString(result);
//            //响应给前端
//            response.getWriter().print(str);
            try {
                Result result = new Result(false, "查询好友列表失败");
                BaseController.printJsonToBrowser(result,response);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
}

